package com.baomidou.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.springboot.ErrorCode;
import com.baomidou.springboot.entity.Post;
import com.baomidou.springboot.entity.TbUser;
import com.baomidou.springboot.entity.vo.PostVO;
import com.baomidou.springboot.mapper.PostMapper;
import com.baomidou.springboot.mapper.TbUserMapper;
import com.baomidou.springboot.mapper.UserMapper;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    PostMapper postMapper;

    @Autowired
    TbUserMapper tbUserMapper;

    @Data @Accessors(chain = true)
    class ListVO {
        Long total;
        List<PostVO> list;
    }
    @GetMapping("/pages")
    public ApiResult list(int page, int limit){
        IPage<Post> postIPage = postMapper.selectPage(new Page<>(page, limit), new QueryWrapper<Post>().lambda().orderByDesc(Post::getCreateAt));
        List<PostVO> list = new ArrayList<>();
        postIPage.getRecords().forEach(v->{
            PostVO postVO = new PostVO();
            BeanUtils.copyProperties(v, postVO);

            TbUser one = tbUserMapper.selectOne(new QueryWrapper<TbUser>().lambda().eq(TbUser::getId, Objects.isNull(v.getUserId()) ? 1 : v.getUserId()));
            BeanUtils.copyProperties(one, postVO);
            list.add(postVO);
        });
        ListVO listVO = new ListVO().setTotal(postIPage.getTotal()).setList(list);
        return ApiResult.restResult(listVO, ErrorCode.SUCCESS);
    }

    @PostMapping("/put-post")
    public ApiResult add(@RequestBody Post msg){
        msg.setUserId(msg.getId());
        msg.setId(null);
        msg.setCreateAt(LocalDateTime.now()).setUpdateAt(LocalDateTime.now());
        if (postMapper.insert(msg)==0) {
            return ApiResult.restResult("文章发送失败", ErrorCode.TEST);
        } else {
            return ApiResult.restResult(msg, ErrorCode.SUCCESS);
        }
    }

}
